import koaRouter from 'koa-router'
import { query, escape, sqlErrorCode } from '@/utils/mySqlConnection'
import { errorRes, successRes } from '@/utils/responseModel'
import { CustomRouterContext } from './index'
import { bodyNotNull } from '@/utils/utils'
import { dataSource } from '@/utils/typeormConnect'
import { Attr } from '@/model/Attr'
import { Group } from '@/model/Group'

const router = new koaRouter<any, CustomRouterContext>()

const attrRepository = dataSource.getRepository(Attr)
const groupRepository = dataSource.getRepository(Group)

router.prefix('/group')


router.post('/updateGroup', async (ctx, next) => {
    const { groupName, groupId = -1 } = ctx.request.body as {
        groupId: number
        groupName: string
    }
    bodyNotNull(ctx, ['groupName'])
    const { userId } = ctx.global.tokenInfo

    const exists = await groupRepository
        .createQueryBuilder()
        .where('userId = :userId', { userId })
        .andWhere('name = :groupName', { groupName })
        .andWhere('id != :groupId', { groupId })
        .andWhere('state = 1')
        .getOne()
    if (exists) {
        ctx.body = new errorRes('存在相同的分类')
    } else {
        if (groupId === -1) {
            await groupRepository
                .createQueryBuilder()
                .insert()
                .values([new Group({ userId, name: groupName })])
                .execute()
        } else {
            bodyNotNull(ctx, ['groupId'])
            await groupRepository
                .createQueryBuilder()
                .update(Group)
                .set({ name: groupName })
                .where('id = :id', { id: groupId })
                .execute()
        }
        ctx.body = new successRes()
    }
})

router.post('/deleteGroup', async (ctx, next) => {
    const { groupId } = ctx.request.body as {
        groupId: number
    }
    bodyNotNull(ctx, ['groupId'])

    await groupRepository
        .createQueryBuilder()
        .delete()
        .from(Group)
        .where('id = :groupId', { groupId })
        .execute()
    ctx.body = new successRes()
})

export default router